package org.wh1tew0lf.vframe.framework;

import java.util.LinkedList;
import java.util.Map;

import org.wh1tew0lf.vframe.framework.vframeexception.VFrameException;

public class VDatabaseOrdership implements IDatabaseRestriction {

	public static final String ASC_ORDER = "ASC";
	public static final String DESC_ORDER = "DESC";

	private LinkedList<VDatabaseOrdershipOrder> orderTypeList = new LinkedList<VDatabaseOrdershipOrder>();
	private LinkedList<VDatabaseField> orderFieldsList = new LinkedList<VDatabaseField>();

	public static VDatabaseOrdership newOrder(String ...args)
			throws VFrameException {
		
		int levels = args.length / 2;
		VDatabaseOrdership result = new VDatabaseOrdership();
		for (int i = 0; i < levels; i++) {
			result.addOrder(VDatabaseField.field(args[i*2]), args[1+i*2]);
		}
		return result;
	}

	public static VDatabaseOrdership newOrder(VDatabaseField field,
			String type) {
		
		return (new VDatabaseOrdership()).addOrder(field, type);
	}

	public VDatabaseOrdership addOrder(String field,
			String type) throws VFrameException {
		if (field == null) {
			return this;
		}
		return this.addOrder(VDatabaseField.field(field), type);
	}

	public VDatabaseOrdership addOrder(VDatabaseField field,
			String type) {
		if (field == null) {
			return this;
		}
		if (type == null) {
			type = ASC_ORDER;
		}
		this.orderFieldsList.add(field);
		if (type.equalsIgnoreCase(DESC_ORDER)) {
			this.orderTypeList.addLast(VDatabaseOrdershipOrder.DESC);
		} else {
			this.orderTypeList.addLast(VDatabaseOrdershipOrder.ASC);
		}
		return this;
	}

	private VDatabaseOrdership() {
	}

	@Override
	public String toString(boolean rawValueData, Map<String, String> nameMap)
			throws VFrameException {
		if (this.orderFieldsList.isEmpty()) {
			return "";
		}
		StringBuffer orderString = new StringBuffer();
		orderString.append("ORDER BY ");
		for (int i = 0; i < this.orderFieldsList.size(); i++) {
			orderString
					.append(this.orderFieldsList.get(i).toString(false, nameMap))
					.append(" ").append(this.orderTypeList.get(i).toString()).append(", ");
		}
		return orderString.substring(0, orderString.length() - 2);
	}

	public boolean isEqualTo(VDatabaseOrdership ordership) {
		if (ordership == null) {
			return false;
		}
		if (this.orderFieldsList.size() != ordership.orderFieldsList.size()) {
			return false;
		}
		for (int i = 0; i < this.orderFieldsList.size(); i++) {
			if (this.orderFieldsList.get(i) != null) {
				if (!(this.orderFieldsList.get(i).isEqualTo(ordership.orderFieldsList.get(i)))) {
					return false;
				} else if (!(this.orderTypeList.get(i).toString().equalsIgnoreCase(ordership.orderTypeList.get(i).toString()))) {
					return false;
				}
			}
		}
		return true;
	}

}
